package com.zs.netlibrary.http;

import android.content.Context;
import com.zs.netlibrary.NetApplication;
import com.zs.netlibrary.http.request.IRequest;
import com.zs.netlibrary.http.request.impl.okhttp.OkRequest;
import com.zs.netlibrary.http.result.ResultCallback;
import com.zs.netlibrary.http.request.factory.impl.DefaultRequestFactory;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

/**
 * http网络访问工具类
 * Created by sheng on 2017/8/15.
 */

public class NetWorkUtils {

    // 单例模式 —— 双重判断
    private volatile static IRequest request;
    private static IRequest getRequest(){
        if(request == null){
            synchronized (DefaultRequestFactory.class) {
                if(request == null)
                    request = DefaultRequestFactory.getInstance().createRequest(OkRequest.class);
            }
        }
        return request;
    }

    public static void init(Context context){
        NetApplication.getInstance().setNetContext(context);
    }

    public static void get(String url, ResultCallback callback){
        get(url, null, callback);
    }

    public static <D> void get(String url,Class<D> cls, ResultCallback callback){
        getRequest().sendGetRequest(new RequestContent(url, new HashMap<String, String>(), cls, callback));
    }



    public static void postForm(String url, Map<String, String> map, ResultCallback callback){
        postForm(url, map, null, callback);
    }

    public static <D> void postForm(String url, Map<String, String> map, Class<D> cls, ResultCallback callback){
        getRequest().sendPostRequest(new RequestContent(url, map, cls, callback));
    }

    public static void postJson(String url, JSONObject jsonObject, ResultCallback callback){
        postJson(url, jsonObject, null, callback);
    }

    public static <D> void postJson(String url, JSONObject jsonObject, Class<D> cls, ResultCallback callback){
        getRequest().sendPostRequest(new RequestContent(url, jsonObject, cls, callback));
    }

    public static <D> void dowmloadFile(String url, Map<String, String> map, ResultCallback callback){
        getRequest().dowmloadFile(new RequestContent(url, map, null, callback));
    }
}
